import os
# coding=utf-8
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.conf import settings
from django import forms
from django.db import models
from django.forms import ModelForm
from django.utils import simplejson
from django.core import serializers


def upload(request):
    if request.method == 'POST':
       file = request.FILES.get('upload', '')
       filename = file.name
       path =  settings.MEDIA_ROOT + '/editor'
       fname = os.path.join(path, filename)
       if os.path.exists(fname): 
         os.remove(fname)
         dirs = os.path.dirname(fname)
         if not os.path.exists(dirs): 
            os.makedirs(dirs) 
         if os.path.isfile(fname):  
            os.remove(fname) 
       fp = open(fname, 'wb') 
       for content in file.chunks(): 
           fp.write(content)
       fp.close()
       result = {"err":"","msg":"/editor/%s" % filename}
       result = simplejson.dumps(result)
       return HttpResponse(result)
    return HttpResponse('302')     